package net.xju3_4.dao;

import net.xju3_4.common.utils.JdbcUtilsV1;
import net.xju3_4.common.utils.MyDbUtil;
import net.xju3_4.entity.OrderEntity;

import java.sql.*;
import java.util.List;

/**
 * 租车数据访问层
 * 独立的租车业务数据访问层
 */
public class RentalDao {

    /**
     * 插入租车订单
     */
    public boolean insertRental(OrderEntity rental) {
        String sql = "INSERT INTO `rental_order` (user_id, car_id, merchant_id, start_time, end_time, rent_days, daily_rent, estimated_total_amount, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = MyDbUtil.getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

            pstmt.setInt(1, rental.getUserId());
            pstmt.setString(2, rental.getCarId());
            pstmt.setString(3, rental.getMerchantId());
            pstmt.setTimestamp(4, new Timestamp(rental.getStartTime().getTime()));
            pstmt.setTimestamp(5, new Timestamp(rental.getEndTime().getTime()));
            pstmt.setString(6, rental.getRentDays());
            pstmt.setString(7, rental.getDailyRent());
            pstmt.setString(8, rental.getEstimatedTotalAmount());
            pstmt.setInt(9, rental.getStatus());

            int result = pstmt.executeUpdate();

            if (result > 0) {
                // 获取生成的主键ID
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    rental.setId(rs.getInt(1));
                    System.out.println("DEBUG: 订单创建成功，生成的订单ID: " + rental.getId());
                }
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    /**
     * 查询用户的租车记录（包含车辆信息）
     */
    public List<OrderEntity> selectUserRentals(String userId, String status, int offset, int pageSize) {
        // 关联查询获取订单和车辆信息
        String sql = "SELECT o.id, o.user_id AS userId, o.car_id AS carId, o.merchant_id AS merchantId, " +
                    "o.start_time AS startTime, o.end_time AS endTime, o.actual_start_time AS actualStartTime, " +
                    "o.actual_end_time AS actualEndTime, o.rent_days AS rentDays, o.daily_rent AS dailyRent, " +
                    "o.estimated_total_amount AS estimatedTotalAmount, o.overtime_fee AS overtimeFee, " +
                    "o.damage_fee AS damageFee, o.final_amount AS finalAmount, o.status, " +
                    "c.brand, c.model, c.license_plate AS licensePlate, c.color, c.images," +
                "m.merchant_name AS merchantName,m.contact_person AS merchantContact,m.contact_phone AS merchantPhone,m.address AS merchantAddress " +
                    "FROM `rental_order` o LEFT JOIN `car` c ON o.car_id = c.id " +
                    "LEFT JOIN merchant m ON o.merchant_id = m.id " + // 新增商家表关联
                    "WHERE o.user_id = ?";


        if (status != null && !status.trim().isEmpty()) {
            sql += " AND o.status = ?";
            sql += " ORDER BY o.id DESC LIMIT ?, ?";
            return JdbcUtilsV1.executeQuery(OrderEntity.class, sql, userId, status, offset, pageSize);
        } else {
            sql += " ORDER BY o.id DESC LIMIT ?, ?";
            return JdbcUtilsV1.executeQuery(OrderEntity.class, sql, userId, offset, pageSize);
        }
    }

    /**
     * 统计用户的租车记录数量
     */
    public int countUserRentals(String userId, String status) {
        String sql = "SELECT COUNT(*) FROM `rental_order` WHERE user_id = ?";

        if (status != null && !status.trim().isEmpty()) {
            sql += " AND status = ?";
            Long count = JdbcUtilsV1.executeQueryOneValue(sql, userId, status);
            return count != null ? count.intValue() : 0;
        } else {
            Long count = JdbcUtilsV1.executeQueryOneValue(sql, userId);
            return count != null ? count.intValue() : 0;
        }
    }

    /**
     * 查询租车订单详情
     */
    public OrderEntity selectRentalDetail(int rentalId, int userId) {
        // 使用明确的字段列表，避免反射类型匹配问题
        String sql = "SELECT " +
                "o.id, o.user_id, o.car_id, o.merchant_id, " +
                "o.start_time, o.end_time, o.actual_start_time, o.actual_end_time, " +
                "o.rent_days, o.daily_rent, o.estimated_total_amount, " +
                "o.overtime_fee, o.damage_fee, o.final_amount, o.status, " +
                "c.brand, c.model, c.images, c.license_plate " +
                "FROM `rental_order` o LEFT JOIN car c ON o.car_id = c.id " +
                "WHERE o.id = ? AND o.user_id = ?";

        try {
            System.out.println("DEBUG: selectRentalDetail - rentalId: " + rentalId + ", userId: " + userId + " (使用JdbcUtilsV1替代MyDbUtil)");
            System.out.println("DEBUG: SQL: " + sql);

            // 使用 JdbcUtilsV1 替代 MyDbUtil
            Connection conn = JdbcUtilsV1.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, rentalId);
            pstmt.setInt(2, userId);

            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                // 手动构建 OrderEntity 对象，避免反射问题
                OrderEntity order = new OrderEntity();

                // 基本订单信息
                order.setId(rs.getInt("id"));
                order.setUserId(rs.getInt("user_id"));
                order.setCarId(rs.getString("car_id"));
                order.setMerchantId(rs.getString("merchant_id"));
                order.setStartTime(rs.getDate("start_time"));
                order.setEndTime(rs.getDate("end_time"));
                order.setActualStartTime(rs.getDate("actual_start_time"));
                order.setActualEndTime(rs.getDate("actual_end_time"));
                order.setRentDays(rs.getString("rent_days"));
                order.setDailyRent(rs.getString("daily_rent"));
                order.setEstimatedTotalAmount(rs.getString("estimated_total_amount"));
                order.setOvertimeFee(rs.getString("overtime_fee"));
                order.setDamageFee(rs.getString("damage_fee"));
                order.setFinalAmount(rs.getString("final_amount"));
                order.setStatus(rs.getInt("status"));

                // 车辆信息
                order.setBrand(rs.getString("brand"));
                order.setModel(rs.getString("model"));
                order.setImages(rs.getString("images"));
                order.setLicensePlate(rs.getString("license_plate"));
                //新增商家信息字段
//                order.setMerchantName(rs.getString("merchantName"));
//                order.setMerchantContact(rs.getString("merchantContact"));
//                order.setMerchantPhone(rs.getString("merchantPhone"));



                System.out.println("DEBUG: 找到订单 - ID: " + order.getId() + ", UserId: " + order.getUserId() + ", Status: " + order.getStatus());

                rs.close();
                pstmt.close();
                JdbcUtilsV1.close();

                return order;
            } else {
                System.out.println("DEBUG: 未找到匹配的订单");

                rs.close();
                pstmt.close();

                // 额外查询：检查订单是否存在（不验证用户ID）
                String checkSql = "SELECT id, user_id FROM `rental_order` WHERE id = ?";
                PreparedStatement checkPstmt = conn.prepareStatement(checkSql);
                checkPstmt.setInt(1, rentalId);
                ResultSet checkRs = checkPstmt.executeQuery();

                if (checkRs.next()) {
                    int existingUserId = checkRs.getInt("user_id");
                    System.out.println("DEBUG: 订单存在但用户ID不匹配 - 订单用户ID: " + existingUserId + ", 请求用户ID: " + userId);
                } else {
                    System.out.println("DEBUG: 订单ID " + rentalId + " 不存在");
                }

                checkRs.close();
                checkPstmt.close();
                JdbcUtilsV1.close();

                return null;
            }
        } catch (Exception e) {
            System.out.println("DEBUG: selectRentalDetail 异常: " + e.getMessage());
            e.printStackTrace();
            JdbcUtilsV1.close();
            return null;
        }
    }

    /**
     * 更新租车订单状态
     */
    public boolean updateRentalStatus(int rentalId, Integer newStatus, String userId) {
        String sql = "UPDATE `rental_order` SET status = ? WHERE id = ? AND user_id = ?";

        try {
            System.out.println("DEBUG: updateRentalStatus - rentalId: " + rentalId + ", newStatus: " + newStatus + ", userId: " + userId);
            System.out.println("DEBUG: SQL: " + sql);

            // 先检查订单是否存在以及用户ID是否匹配
            String checkSql = "SELECT id, user_id, status FROM `rental_order` WHERE id = ?";
            Connection conn = JdbcUtilsV1.getConnection();
            PreparedStatement checkPstmt = conn.prepareStatement(checkSql);
            checkPstmt.setInt(1, rentalId);
            ResultSet checkRs = checkPstmt.executeQuery();

            if (checkRs.next()) {
                int existingUserId = checkRs.getInt("user_id");
                int currentStatus = checkRs.getInt("status");
                System.out.println("DEBUG: 找到订单 - ID: " + rentalId + ", 实际用户ID: " + existingUserId + ", 当前状态: " + currentStatus + ", 请求用户ID: " + userId);

                if (existingUserId != Integer.parseInt(userId)) {
                    System.out.println("DEBUG: 用户ID不匹配，无法更新订单状态");
                    checkRs.close();
                    checkPstmt.close();
                    JdbcUtilsV1.close();
                    return false;
                }
            } else {
                System.out.println("DEBUG: 订单ID " + rentalId + " 不存在");
                checkRs.close();
                checkPstmt.close();
                JdbcUtilsV1.close();
                return false;
            }

            checkRs.close();
            checkPstmt.close();
            JdbcUtilsV1.close();

            // 将 String userId 转换为 int，因为数据库字段是 INT 类型
            int userIdInt = Integer.parseInt(userId);
            int result = MyDbUtil.executeUpdate(sql, newStatus, rentalId, userIdInt);

            System.out.println("DEBUG: 更新结果: " + result + " 行受影响");
            return result > 0;
        } catch (Exception e) {
            System.out.println("DEBUG: updateRentalStatus 异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 统计指定时间段内的冲突租车记录
     */
    public int countConflictRentals(String carId, String startDate, String endDate) {
        String sql = "SELECT COUNT(*) FROM `rental_order` WHERE car_id = ? AND status NOT IN (3, 5) AND ((start_time <= ? AND end_time >= ?) OR (start_time <= ? AND end_time >= ?) OR (start_time >= ? AND end_time <= ?))";

        try {
            Long count = JdbcUtilsV1.executeQueryOneValue(sql, carId, startDate, startDate, endDate, endDate, startDate, endDate);
            return count != null ? count.intValue() : 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将ResultSet映射为OrderEntity对象
     */
    private OrderEntity mapResultSetToOrder(ResultSet rs) throws SQLException {
        OrderEntity order = new OrderEntity();

        order.setId(rs.getInt("id"));
        order.setUserId(Integer.parseInt(rs.getString("user_id")));
        order.setCarId(rs.getString("car_id"));
        order.setMerchantId(rs.getString("merchant_id"));
        order.setStartTime(rs.getTimestamp("start_time"));
        order.setEndTime(rs.getTimestamp("end_time"));
        order.setActualStartTime(rs.getTimestamp("actual_start_time"));
        order.setActualEndTime(rs.getTimestamp("actual_end_time"));
        order.setRentDays(rs.getString("rent_days"));
        order.setDailyRent(rs.getString("daily_rent"));
        order.setEstimatedTotalAmount(rs.getString("estimated_total_amount"));
        order.setOvertimeFee(rs.getString("overtime_fee"));
        order.setDamageFee(rs.getString("damage_fee"));
        order.setFinalAmount(rs.getString("final_amount"));
        order.setStatus(Integer.parseInt(rs.getString("status")));

        return order;
    }
}
